#!/usr/bin/python3

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

import random as r

import time

def click_label(driver, label_id):
    target_labels = driver.find_elements_by_id(label_id)
    if not len(target_labels) == 1: 
        return False
    target_labels[0].click()

def ReportOnce(username, passwd):
    print("$>$>$> prepare report for " + username)
    chrome_options = Options()
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--headless')
    chrome_options.add_argument("--window-size=1920,1080");
    driver = webdriver.Chrome(options=chrome_options)
    driver.maximize_window()
    driver.get('http://jkrb.xjtu.edu.cn/EIP/user/index.htm')
    driver.set_page_load_timeout(10)

    # #login system
    try:
        username_editor = driver.find_element_by_xpath('//*[@id="form1"]/input[1]')
        password_editor = driver.find_element_by_xpath('//*[@id="form1"]/input[2]')
        username_editor.send_keys(username)
        password_editor.send_keys(passwd)
        driver.find_element_by_xpath('/html/body/div/div[1]/div[2]/div[2]/div[1]/div[3]').click()
    except:
        import traceback
        traceback.print_exc()
        print("Something wrong in login page!")
        driver.quit()
        return False

    time.sleep(2)
    try:
        driver.switch_to.default_content()
        driver.switch_to.frame(0)
        driver.switch_to.frame(1)
        time.sleep(0.5)
        iframes = driver.find_elements_by_class_name('service-hall-name')
        for iframe in iframes:
            if iframe.text == "研究生每日健康状况填报":
                iframe.click()
                break
    except:
        import traceback
        traceback.print_exc()
        print("Something wrong on select btn: 研究生每日健康状况填报!")
        driver.quit()
        return False

    time.sleep(0.5)
    try:
        driver.switch_to.default_content()
        driver.switch_to.frame(1)
        time.sleep(0.5)
        buttons = driver.find_elements_by_class_name('business-btn-text')
        for button in buttons:
            if button.text == "返校登记后每日健康填报":
                button.click()
                break
    except:
        import traceback
        traceback.print_exc()
        print("Something wrong on select btn: 返校登记后每日健康填报!")
        driver.quit()
        return False

    time.sleep(2)
    try:
        driver.switch_to.default_content()
        driver.switch_to.frame(2)
        time.sleep(0.5)
        message_box_elements = driver.find_elements_by_class_name('mini-messagebox-content-text')
        if len(message_box_elements) >= 1:
            print(message_box_elements[0].text)            
            driver.quit()
            return True
    except:
        import traceback
        traceback.print_exc()
        print("Something Wrong on prase message box!")
        driver.quit()
        return False
        
    print("$>$>$> begin report for " + username)
    time.sleep(2)
    try:  
        driver.switch_to.frame(0)

        click_label(driver, 'mini-2$ck$2')

        m_temperature = driver.find_elements_by_id('BRTW$text')
        if not len(m_temperature) == 1: 
            driver.quit()
            return False

        m_temperature[0].send_keys("%0.1f" % (35.9 + r.uniform(0.0, 0.7)))

        click_label(driver, "mini-95$1")
        click_label(driver, "mini-99$1")

        driver.switch_to.default_content()
        driver.switch_to.frame(2)
        click_label(driver, 'sendBtn')

        confirm_btns = driver.find_elements_by_class_name('mini-button-text')
        for confirm_btn in confirm_btns:
            if confirm_btn.text == '确定':
                confirm_btn.click()
                break

        error_msg_content = driver.find_elements_by_class_name('mini-messagebox-content-text')
        if(len(error_msg_content) >= 1):
            print(error_msg_content[0].text)
        else:
            driver.switch_to.frame(0)
            error_msg_content = driver.find_elements_by_class_name('mini-messagebox-content-text')
            if(len(error_msg_content) >= 1):
                print(error_msg_content[0].text)
                if error_msg_content[0].text == '上午只许发起一条，不允许重复发起！' or error_msg_content[0].text == '下午只许发起一条，不允许重复发起！':
                    driver.quit()
                    return True
        driver.quit()
        return False
    except:
        import traceback
        traceback.print_exc()
        print("Something Wrong on report!")
        driver.quit()
        return False

def main():
    while not ReportOnce("login_name_0", "password_0"):
        time.sleep(2)
    time.sleep(5)

    # while not ReportOnce("login_name_1", "password_1"):
    #     time.sleep(2)
    # time.sleep(5)

    # ...

if __name__ == "__main__":
    print(">>>>>>>>>>>>> 自动填报系统 <<<<<<<<<<<<<<")
    local_time = time.localtime(time.time())
    print(">>>>>>>>> %s <<<<<<<<<<<" % time.strftime('%Y-%m-%d %H:%M:%S', local_time) )
    main()
    print("#########################################")